package com.gqemf.schedule;

import com.gqemf.entity.Emfhistory;
import com.gqemf.service.EmfService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FilenameFilter;
import java.util.*;

/**
 * @author chan
 */
@Slf4j
@NoArgsConstructor
@Component
public class ScheduledTasks {

    //private final String FILE_PATH = "D:\\emfrecorders\\";

    private final String FILE_PATH = "C:\\Users\\super\\AppData\\Local\\VirtualStore\\Program Files (x86)\\GQ EMF PRO";

    private EmfService emfService;

    @Autowired
    public ScheduledTasks(EmfService emfService) {
        this.emfService = emfService;
    }

    @Scheduled(fixedDelay = 500000)
    public void readDataFile() {
        log.info("reading csv");
        //遍历文件夹下所有文件，拿取数据，去重，最后留下最新的文件，最新的文件 数据多，前两个最新的文件
        File[] csvFiles = getLatestTwoFiles(FILE_PATH);
        if(csvFiles[0] == null || csvFiles[0].length() <= 0){
            log.info("there is no csv files which can be read inside!");
            return;
        }
        List<Emfhistory> latestList = emfService.convertFromRecorders(csvFiles[0]);
        if(csvFiles[1] != null){
            //最新的文件-老文件
            List<Emfhistory> oldList = emfService.convertFromRecorders(csvFiles[1]);
            latestList.removeAll(oldList);
        }
        if(emfService.checkIfLatestData(latestList)) {
            Integer index = emfService.saveEmfRecorders(latestList);
            log.info("we have saved " + index);
        }else {
            log.info("these are old data! Please wait ......");
        }
    }

    @Scheduled(fixedDelay = 550000)
    public void clearBinFiles(){
        deleteFiles(FILE_PATH,".bin");
    }

    public boolean forceDelete(File file){
        boolean result=file.delete();
        if (!result) {
            System.gc();    //回收资源
            file.delete();
        }
        return result;
    }

    public File[] getLatestTwoFiles(String folderPath){
        File[] latestTwoFiles = new File[2];
        File path=new File(folderPath);
        //列出该目录下所有文件和文件夹
        File[] files = path.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                //把dir 和name都封装到一个文件对象里
                File file = new File(dir, name);
                return file.isFile() && file.getName().endsWith(".csv");
            }
        });
        //按照目录中文件最后修改日期实现倒序排序
        if(files.length >= 2) {
            Arrays.sort(files, new Comparator<File>() {
                @Override
                public int compare(File file1, File file2) {
                    return (int) (file2.lastModified() - file1.lastModified());
                }
            });
            //取最新修改的文件，get文件名
            latestTwoFiles[0] = files[0];
            latestTwoFiles[1] = files[1];
            //删除除前两个最新文件以外的文件
            for(int i = 0; i < files.length; i++){
                if(i >= 2 && forceDelete(files[i])){
                    log.info("deleted " + i);
                }
            }
        }else {
            latestTwoFiles[0] = files[0];
        }
        return latestTwoFiles;
    }

    public void deleteFiles(String folderPath, String endWith){
        File path=new File(folderPath);
        //列出该目录下所有文件和文件夹
        File[] files = path.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                //把dir 和name都封装到一个文件对象里
                File file = new File(dir, name);
                return file.isFile() && file.getName().endsWith(endWith);
            }
        });
        if(files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                forceDelete(files[i]);
            }
        }else {
            log.info("there is no "+ endWith +" files");
        }
    }
}
